<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkContact\Logic;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\WorkContact\Action\Dashboard\Traits\ContactStageUpdateTrait;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\WeWork\WeWork;
use Psr\Container\ContainerInterface;

/**
 * 删除企业客户回调.
 *
 * Class UpdateContactStageCallBackLogic
 */
class UpdateContactStageCallBackLogic
{
    use ContactStageUpdateTrait;

    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var WeWork
     */
    protected $client;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * 客户表.
     * @Inject
     * @var WorkContactContract
     */
    private $contact;

    /**
     * @Inject
     * @var CorpContract
     */
    private $corpService;

    /**
     * 员工表.
     * @Inject
     * @var WorkEmployeeContract
     */
    private $employee;

    public function handle(array $wxResponse): void
    {
        Db::beginTransaction();
        try {
            // 阶段自动化
            if (! isset($message['UserID'], $message['ExternalUserID'])) {
                return;
            }

            // 查询客户id,查询员工id
            [$contactId, $employeeId,$corpId] = $this->employeeAndContactData($message['ToUserName'], $message['UserID'], $message['ExternalUserID']);
            if ($contactId === 0 || $employeeId === 0 || $corpId === 0) {
                return;
            }

            $this->contactStageUpdate($contactId, $employeeId, $corpId);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }
    }

    /**
     * 获取员工与客户ID.
     * @param string $wxUserId ...
     * @param string $wxContactUserId ...
     * @return array ...
     */
    protected function employeeAndContactData(string $wxCorpId, string $wxUserId, string $wxContactUserId): array
    {
        $contactId = 0;
        $employeeId = 0;
        $contactInfo = $this->contact->getWorkContactByWxExternalUserId($wxContactUserId, ['id', 'unionid']);
        if (! empty($contactInfo)) {
            $contactId = $contactInfo['id'];
        }

        $corp = $this->corpService->getCorpByWxCorpId($wxCorpId, ['id']);

        if (empty($corp)) {
            return [$contactId, $employeeId];
        }

        $employeeInfo = $this->employee->getWorkEmployeeByWxUserIdCorpIdWithTrashed($wxUserId, (int) $corp['id'], ['id']);
        if (! empty($employeeInfo)) {
            $employeeId = $employeeInfo['id'];
        }

        return [$contactId, $employeeId, empty($corp['id']) ? 0 : $corp['id']];
    }
}
